<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户查询 - 图书馆管理系统</title>
    
    <!-- LayUI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/layui@2.8.18/dist/css/layui.css">
    
    <!-- Custom CSS -->
    <style>
        body {
            background-color: #f2f2f2;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
        }
        
        .main-container {
            margin: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header-section {
            background: linear-gradient(135deg, #5FB878 0%, #009688 100%);
            color: white;
            padding: 20px 30px;
        }
        
        .header-section h1 {
            margin: 0;
            font-size: 20px;
            font-weight: 500;
        }
        
        .search-section {
            padding: 20px 30px;
            border-bottom: 1px solid #e6e6e6;
            background: #fafafa;
        }
        
        .content-section {
            padding: 20px 30px;
        }
        
        .layui-form-item {
            margin-bottom: 15px;
        }
        
        .layui-form-label {
            width: 80px;
            padding: 9px 10px;
            font-weight: 500;
            color: #333;
        }
        
        .layui-input-inline {
            width: 180px;
        }
        
        .search-btn-group {
            margin-left: 10px;
        }
        
        .toolbar {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .toolbar-left {
            display: flex;
            gap: 10px;
        }
        
        .toolbar-right {
            display: flex;
            gap: 10px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            color: white;
            text-align: center;
            min-width: 40px;
        }
        
        .status-active { background-color: #5FB878; }
        .status-frozen { background-color: #FF5722; }
        .status-graduated { background-color: #999; }
        
        .usertype-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
            text-align: center;
            min-width: 40px;
        }
        
        .usertype-student { background-color: #1E9FFF; }
        .usertype-teacher { background-color: #FF9800; }
        .usertype-admin { background-color: #9C27B0; }
        
        .action-btn {
            margin: 0 2px;
            padding: 2px 8px;
            font-size: 12px;
            border-radius: 3px;
        }
        
        .layui-table-cell {
            height: auto !important;
            padding: 8px 10px;
        }
        
        /* 模态窗口样式 */
        .layui-layer-iframe {
            border-radius: 8px;
            overflow: hidden;
        }
        
        .layui-layer-title {
            background: linear-gradient(135deg, #5FB878 0%, #009688 100%);
            color: white;
            border: none;
        }
        
        @media (max-width: 768px) {
            .main-container {
                margin: 10px;
                border-radius: 0;
            }
            
            .search-section,
            .content-section {
                padding: 15px 20px;
            }
            
            .toolbar {
                flex-direction: column;
                align-items: stretch;
                gap: 10px;
            }
            
            .toolbar-left,
            .toolbar-right {
                justify-content: center;
            }
        }
    </style>

    
</head>
<body>
    <div class="main-container">
        <!-- Header Section -->
        <div class="header-section">
            <h1><i class="layui-icon layui-icon-user"></i> 用户查询管理</h1>
        </div>
        
        <!-- Search Section -->
        <div class="search-section">
            <form class="layui-form" id="searchForm" lay-filter="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="username" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">姓名</label>
                        <div class="layui-input-inline">
                            <input type="text" name="realName" placeholder="请输入真实姓名" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用户类型</label>
                        <div class="layui-input-inline">
                            <select name="userType">
                                <option value="">全部类型</option>
                                <option value="student">学生</option>
                                <option value="teacher">教师</option>
                                <option value="admin">管理员</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-inline">
                            <select name="status">
                                <option value="">全部状态</option>
                                <option value="active">正常</option>
                                <option value="frozen">冻结</option>
                                <option value="graduated">毕业</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline search-btn-group">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="searchSubmit">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Content Section -->
        <div class="content-section">
            <!-- Toolbar -->
            <div class="toolbar">
                <div class="toolbar-left">
                    <button class="layui-btn layui-btn-normal" id="addUserBtn">
                        <i class="layui-icon layui-icon-add-1"></i> 增加
                    </button>
                    <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                        <i class="layui-icon layui-icon-delete"></i> 批量删除
                    </button>
                    <button class="layui-btn layui-btn-warm" id="exportBtn">
                        <i class="layui-icon layui-icon-export"></i> 导出
                    </button>
                </div>
                <div class="toolbar-right">
                    <button class="layui-btn layui-btn-primary layui-btn-sm" id="refreshBtn">
                        <i class="layui-icon layui-icon-refresh-3"></i> 刷新
                    </button>
                    <button class="layui-btn layui-btn-primary layui-btn-sm" id="printBtn">
                        <i class="layui-icon layui-icon-print"></i> 打印
                    </button>
                </div>
            </div>
            
            <!-- Data Table -->
            <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
        </div>
    </div>

    <!-- 表格行工具栏模板 -->
    <script type="text/html" id="userTableToolbar">
        <a class="layui-btn layui-btn-xs action-btn" lay-event="detail" title="查看详情">
            <i class="layui-icon layui-icon-about"></i> 详情
        </a>
        <a class="layui-btn layui-btn-normal layui-btn-xs action-btn" lay-event="edit" title="编辑">
            <i class="layui-icon layui-icon-edit"></i> 编辑
        </a>
        <a class="layui-btn layui-btn-warm layui-btn-xs action-btn" lay-event="resetPassword" title="重置密码">
            <i class="layui-icon layui-icon-password"></i> 重置
        </a>
        {{# if(d.status === 'active') { }}
        <a class="layui-btn layui-btn-danger layui-btn-xs action-btn" lay-event="freeze" title="冻结">
            <i class="layui-icon layui-icon-pause"></i> 冻结
        </a>
        {{# } else if(d.status === 'frozen') { }}
        <a class="layui-btn layui-btn-normal layui-btn-xs action-btn" lay-event="activate" title="激活">
            <i class="layui-icon layui-icon-play"></i> 激活
        </a>
        {{# } }}
        <a class="layui-btn layui-btn-danger layui-btn-xs action-btn" lay-event="delete" title="删除">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </a>
    </script>

    <!-- 用户类型模板 -->
    <script type="text/html" id="userTypeTpl">
        {{# if(d.userType === 'student') { }}
        <span class="usertype-badge usertype-student">学生</span>
        {{# } else if(d.userType === 'teacher') { }}
        <span class="usertype-badge usertype-teacher">教师</span>
        {{# } else if(d.userType === 'admin') { }}
        <span class="usertype-badge usertype-admin">管理员</span>
        {{# } else { }}
        <span class="usertype-badge" style="background-color: #999;">{{d.userType}}</span>
        {{# } }}
    </script>

    <!-- 状态模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.status === 'active') { }}
        <span class="status-badge status-active">正常</span>
        {{# } else if(d.status === 'frozen') { }}
        <span class="status-badge status-frozen">冻结</span>
        {{# } else if(d.status === 'graduated') { }}
        <span class="status-badge status-graduated">毕业</span>
        {{# } else { }}
        <span class="status-badge" style="background-color: #999;">{{d.status}}</span>
        {{# } }}
    </script>

    <!-- LayUI JS -->
    <script src="https://unpkg.com/layui@2.8.18/dist/layui.js"></script>
    <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>

    
    <script>
        layui.use(['table', 'form', 'layer', 'util', 'laydate'], function(){
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var util = layui.util;
            var $ = layui.$;
            
            // API配置
            var API_BASE_URL = 'http://localhost:8081/api';
            
            // 初始化表格
            var userTableIns = table.render({
                elem: '#userTable',
                url: API_BASE_URL + '/users',
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                response: {
                    statusName: 'success',
                    statusCode: true,
                    msgName: 'message',
                    countName: 'total',
                    dataName: 'records'
                },
                parseData: function(res) {
                    console.log('API响应数据:', res); // 调试日志
                    return {
                        "success": res.success,
                        "message": res.message,
                        "total": res.data ? res.data.total : 0,
                        "records": res.data ? res.data.users : []
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'userId', title: 'ID', width: 80, sort: true},
                    {field: 'username', title: '用户名', width: 120},
                    {field: 'realName', title: '姓名', width: 100},
                    {field: 'userType', title: '用户类型', width: 100, templet: '#userTypeTpl'},
                    {field: 'studentId', title: '学号/工号', width: 120},
                    {field: 'classDepartment', title: '班级/部门', width: 150},
                    {field: 'phone', title: '手机号码', width: 120},
                    {field: 'email', title: '邮箱', width: 180},
                    {field: 'status', title: '状态', width: 80, templet: '#statusTpl'},
                    {field: 'maxBorrowBooks', title: '最大借书数', width: 100, align: 'center'},
                    {field: 'registrationDate', title: '注册日期', width: 120, templet: function(d) {
                        return d.registrationDate || '-';
                    }},
                    {title: '操作', width: 300, toolbar: '#userTableToolbar', fixed: 'right'}
                ]],
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                    groups: 5,
                    limits: [10, 20, 50, 100],
                    limit: 10
                },
                loading: true,
                height: 'full-200',
                even: true,
                size: 'sm',
                done: function(res, curr, count) {
                    console.log('表格数据加载完成:', res);
                    console.log('当前页:', curr);
                    console.log('数据总数:', count);
                },
                error: function(res, msg) {
                    console.error('表格数据加载失败:', res, msg);
                    layer.msg('查询用户列表失败: ' + (msg || '网络错误'), {icon: 2});
                }
            });
            
            // 搜索表单提交
            form.on('submit(searchSubmit)', function(data) {
                var field = data.field;
                
                // 构建搜索关键词
                var keyword = '';
                if (field.username) {
                    keyword = field.username;
                } else if (field.realName) {
                    keyword = field.realName;
                }
                
                // 重新加载表格数据
                userTableIns.reload({
                    where: {
                        userType: field.userType,
                        status: field.status,
                        keyword: keyword // 后端使用keyword参数进行模糊搜索
                    },
                    page: {
                        curr: 1 // 重新从第一页开始
                    }
                });
                
                return false; // 阻止表单跳转
            });
            
            // 重置搜索表单
            form.on('submit(searchReset)', function(data) {
                document.getElementById('searchForm').reset();
                form.render();
                
                // 重新加载表格数据
                userTableIns.reload({
                    where: {},
                    page: {
                        curr: 1
                    }
                });
                
                return false;
            });
            
            // 工具栏事件
            $('#addUserBtn').on('click', function() {
                openUserAddModal();
            });
            
            $('#batchDeleteBtn').on('click', function() {
                var checkStatus = table.checkStatus('userTable');
                var data = checkStatus.data;
                
                if(data.length === 0) {
                    layer.msg('请选择要删除的用户', {icon: 2});
                    return;
                }
                
                layer.confirm('确定要删除选中的 ' + data.length + ' 个用户吗？', {
                    icon: 3,
                    title: '批量删除确认'
                }, function(index) {
                    var userIds = data.map(function(item) {
                        return item.userId;
                    });
                    
                    batchDeleteUsers(userIds);
                    layer.close(index);
                });
            });
            
            $('#exportBtn').on('click', function() {
                layer.msg('导出功能开发中...', {icon: 1});
            });
            
            $('#refreshBtn').on('click', function() {
                userTableIns.reload();
                layer.msg('数据已刷新', {icon: 1, time: 1000});
            });
            
            $('#printBtn').on('click', function() {
                layer.msg('打印功能开发中...', {icon: 1});
            });
            
            // 表格行工具事件
            table.on('tool(userTable)', function(obj) {
                var data = obj.data;
                var layEvent = obj.event;
                
                switch(layEvent) {
                    case 'detail':
                        showUserDetail(data);
                        break;
                    case 'edit':
                        editUser(data);
                        break;
                    case 'resetPassword':
                        resetUserPassword(data);
                        break;
                    case 'freeze':
                        changeUserStatus(data.userId, 'frozen', '冻结');
                        break;
                    case 'activate':
                        changeUserStatus(data.userId, 'active', '激活');
                        break;
                    case 'delete':
                        deleteUser(data);
                        break;
                }
            });
            
            // 打开用户添加模态窗口
            function openUserAddModal() {
                layer.open({
                    type: 2,
                    title: '<i class="layui-icon layui-icon-user"></i> 添加用户',
                    shadeClose: false,
                    shade: [0.3, '#000'],
                    maxmin: true,
                    area: ['900px', '700px'],
                    content: 'layui_user_add.html',
                    success: function(layero, index) {
                        // 监听iframe加载完成
                        var iframe = layero.find('iframe')[0];
                        iframe.onload = function() {
                            // 可以在这里与iframe页面进行通信
                            console.log('用户添加页面加载完成');
                        };
                    },
                    end: function() {
                        // 模态窗口关闭时刷新表格
                        userTableIns.reload();
                    }
                });
            }
            
            // 显示用户详情
            function showUserDetail(data) {
                var content = `
                    <div style="padding: 20px; line-height: 1.8;">
                        <div><strong>用户ID:</strong> ${data.userId}</div>
                        <div><strong>用户名:</strong> ${data.username}</div>
                        <div><strong>真实姓名:</strong> ${data.realName}</div>
                        <div><strong>用户类型:</strong> ${getUserTypeName(data.userType)}</div>
                        <div><strong>学号/工号:</strong> ${data.studentId || '-'}</div>
                        <div><strong>班级/部门:</strong> ${data.classDepartment || '-'}</div>
                        <div><strong>手机号码:</strong> ${data.phone || '-'}</div>
                        <div><strong>邮箱地址:</strong> ${data.email || '-'}</div>
                        <div><strong>用户状态:</strong> ${getUserStatusName(data.status)}</div>
                        <div><strong>最大借书数:</strong> ${data.maxBorrowBooks || '-'} 本</div>
                        <div><strong>当前借阅数:</strong> ${data.currentBorrowCount || 0} 本</div>
                        <div><strong>注册日期:</strong> ${data.registrationDate || '-'}</div>
                    </div>
                `;
                
                layer.open({
                    type: 1,
                    title: '<i class="layui-icon layui-icon-about"></i> 用户详情 - ' + data.realName,
                    shadeClose: true,
                    shade: [0.3, '#000'],
                    area: ['500px', '600px'],
                    content: content
                });
            }
            
            // 编辑用户
            function editUser(data) {
                layer.msg('编辑功能开发中...', {icon: 1});
                // TODO: 实现编辑用户功能
            }
            
            // 重置用户密码
            function resetUserPassword(data) {
                layer.confirm('确定要重置用户 "' + data.realName + '" 的密码吗？', {
                    icon: 3,
                    title: '重置密码确认'
                }, function(index) {
                    $.ajax({
                        url: API_BASE_URL + '/users/' + data.userId + '/reset-password',
                        type: 'POST',
                        data: { newPassword: '123456' }, // 默认密码
                        success: function(response) {
                            if(response.success) {
                                layer.msg('密码重置成功，新密码为：123456', {icon: 1, time: 3000});
                            } else {
                                layer.msg(response.message || '密码重置失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('密码重置失败，请稍后重试', {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            }
            
            // 更改用户状态
            function changeUserStatus(userId, status, actionName) {
                layer.confirm('确定要' + actionName + '该用户吗？', {
                    icon: 3,
                    title: actionName + '确认'
                }, function(index) {
                    var url = status === 'active' 
                        ? API_BASE_URL + '/users/' + userId + '/activate'
                        : API_BASE_URL + '/users/' + userId + '/freeze';
                    
                    $.ajax({
                        url: url,
                        type: 'POST',
                        success: function(response) {
                            if(response.success) {
                                layer.msg(actionName + '成功', {icon: 1});
                                userTableIns.reload();
                            } else {
                                layer.msg(response.message || actionName + '失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg(actionName + '失败，请稍后重试', {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            }
            
            // 删除用户
            function deleteUser(data) {
                layer.confirm('确定要删除用户 "' + data.realName + '" 吗？', {
                    icon: 3,
                    title: '删除确认'
                }, function(index) {
                    $.ajax({
                        url: API_BASE_URL + '/users/' + data.userId,
                        type: 'DELETE',
                        success: function(response) {
                            if(response.success) {
                                layer.msg('删除成功', {icon: 1});
                                userTableIns.reload();
                            } else {
                                layer.msg(response.message || '删除失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('删除失败，请稍后重试', {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            }
            
            // 批量删除用户
            function batchDeleteUsers(userIds) {
                $.ajax({
                    url: API_BASE_URL + '/users/batch-delete',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(userIds),
                    success: function(response) {
                        if(response.success) {
                            layer.msg('批量删除成功', {icon: 1});
                            userTableIns.reload();
                        } else {
                            layer.msg(response.message || '批量删除失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('批量删除失败，请稍后重试', {icon: 2});
                    }
                });
            }
            
            // 获取用户类型显示名称
            function getUserTypeName(userType) {
                switch(userType) {
                    case 'student': return '学生';
                    case 'teacher': return '教师';
                    case 'admin': return '管理员';
                    default: return userType;
                }
            }
            
            // 获取用户状态显示名称
            function getUserStatusName(status) {
                switch(status) {
                    case 'active': return '正常';
                    case 'frozen': return '冻结';
                    case 'graduated': return '毕业';
                    default: return status;
                }
            }
        });
    </script>
</body>
</html>